package in.muton.edushare.registration;

import in.muton.edushare.EduSharePage;
import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.EduShareLogin;
import in.muton.edushare.wicket.models.CayenneModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;

import com.edushare.common.dao.UsersDAO;
import com.edushare.common.vo.Users;

public class ForgotPasswordKeyVerify extends EduSharePage {
	
	private String password1;
	private String password2;
	private CayenneModel<Users> userModel;
	private static Log log = LogFactory.getLog(ForgotPasswordKeyVerify.class);
	
	public ForgotPasswordKeyVerify(PageParameters p){
		getSession().bind();
		final WebMarkupContainer wmc = new WebMarkupContainer("homeLink");
		wmc.add(new Link<Object>("homePageLink"){
			private static final long serialVersionUID = -4823234097530084778L;
			@Override
			public void onClick() {
				setResponsePage(EduShareLogin.class);
			}
		});
		wmc.setVisible(false);
		
		String confKey = p.getString("key");
		final Users u = new UsersDAO(getSessionORMInterface()).validateEmailInvite(confKey);
		Form<Object> f = new Form<Object>("form"){
			private static final long serialVersionUID = 4498118852927968284L;
			@Override
			public void onSubmit(){
				if(password1.compareTo(password2) == 0){
					log.debug("Password1: "+ password1);
					userModel.getObject().setPassword(password1);
					userModel.getObject().setConfKey("0");
					EduShareSession.get().getSessionORMInterface().commitAllChanges();
					wmc.setVisible(true);
					this.setVisible(false);
				}else{
					error("Error : Password and Confirm password are different");
				}
			}
		};
		setDefaultModel(new CompoundPropertyModel<String>(this));
		f.add(wmc);
		f.add(new FeedbackPanel("feedback"));
		f.add(new PasswordTextField("password1"));
		f.add(new PasswordTextField("password2"));
		add(f);
		
		if(u!=null){
			this.userModel = new CayenneModel<Users>(u);
			f.setVisible(true);
		}else{
			error("Sorry, but the key you provided is not valid");
			f.setVisible(false);
		}
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getPassword2() {
		return password2;
	}
}
